package com.example.firstapp.core;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

public class CalculateDistanceThread extends Thread {
	private int dist;
	private String urlStr;

	public CalculateDistanceThread(String url) {
		this.urlStr = url;
	}

	@Override
	public void run() {
		try {
			URL url = new URL(urlStr);

			// Creating an http connection to communicate with url
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			// Connecting to url
			urlConnection.connect();

			// Reading data from url
			InputStream is = urlConnection.getInputStream();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "UTF-8"));
			StringBuilder builder = new StringBuilder();
			for (String line = null; (line = reader.readLine()) != null;) {
				builder.append(line).append("\n");
			}
			JSONObject jsonObj = new JSONObject(builder.toString());
			JSONArray rowsArray = jsonObj.getJSONArray("rows");
			JSONObject rowsObject = rowsArray.getJSONObject(0);
			JSONArray elementsArray = rowsObject.getJSONArray("elements");
			JSONObject elementsObject = elementsArray.getJSONObject(0);
			JSONObject distanceObject = elementsObject
					.getJSONObject("distance");
			dist = distanceObject.getInt("value");
		} catch (Exception e) {
			dist = 100000;
		}
	}

	public int getDist() {
		return dist;
	}

}
